<!-- src/components/BarChart.vue -->
<template>
  <div ref="chartEl" style="height: 100%;"></div>
</template>

<script setup>
import { ref, onMounted, watch, onBeforeUnmount } from 'vue'
import { defineProps } from 'vue';
import * as echarts from 'echarts'

const props = defineProps({
  data: {
    type: Object,
    required: true,
    default: () => ({
      categories: [],
      values: []
    })
  }
})

const chartEl = ref(null)
let chartInstance = null

const initChart = () => {
  if (!chartEl.value) return

  chartInstance = echarts.init(chartEl.value)
  updateChart()

  // 响应窗口变化
  const resizeHandler = () => chartInstance.resize()
  window.addEventListener('resize', resizeHandler)
  onBeforeUnmount(() => window.removeEventListener('resize', resizeHandler))
}

const updateChart = () => {
  if (!chartInstance) return

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    xAxis: {
      type: 'category',
      data: props.data.categories,
      axisLabel: { rotate: 45 }
    },
    yAxis: { type: 'value' },
    series: [{
      data: props.data.values,
      type: 'bar',
      itemStyle: {
        color: '#1890ff',
        borderRadius: [4, 4, 0, 0]
      },
      barWidth: '60%'
    }],
    grid: {
      containLabel: true,
      left: '3%',
      right: '3%',
      bottom: '10%'
    }
  }

  chartInstance.setOption(option)
}

onMounted(initChart)
watch(() => props.data, updateChart, { deep: true })
</script>